//
//  DYWPickerSelector.swift
//  sinaWeibo
//
//  Created by 董艳武 on 16/3/1.
//  Copyright © 2016年 董艳武. All rights reserved.
//

import UIKit
import SnapKit
import HMImagePicker
// 设置可重用标识符
private let reuseIdentifier = "pickerSelectorCell"
// 间距
private let picsMargin:CGFloat = 5
// 最大的 cell 的数目
private let maxCellNumber:Int = 9
class DYWPickerSelector: UICollectionViewController {
    /// 图片数组属性
    lazy var images = [UIImage]()
    
    /// 选中的图片数组属性
    private lazy var selectedAssets = [PHAsset]()
    init() {
        let flowLayOut = UICollectionViewFlowLayout()
        let cellWidth = (screenWidth - 5 * picsMargin) / 4
        flowLayOut.itemSize = CGSizeMake(cellWidth, cellWidth)
        flowLayOut.minimumInteritemSpacing = picsMargin
        flowLayOut.minimumLineSpacing = picsMargin
        flowLayOut.sectionInset = UIEdgeInsets(top: picsMargin, left: picsMargin, bottom: 0, right: picsMargin)
        super.init(collectionViewLayout: flowLayOut)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.registerClass(pickerSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        self.collectionView!.backgroundColor = LightBlue
    }

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 当显示九张图片的时候就不在显示添加图片的按钮
        return images.count + (self.images.count == maxCellNumber ? 0 : 1)
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)  as! pickerSelectorCell
//        cell.deleteBtn.hidden = true
        cell.delegate = self
        /*
        当 image.count == indexPath.item 显示的是最后一条数据，即是添加图片的按钮,每一次 reloadData 这个方法就会重复执行 ，若使用 image.count != 0 则会出现数组越界的情况，原因是此时数组中只有1条数据，显示的却是2个 cell ，显示第二个 cell 的时候回出现数组越界的情况,还是需要判断 imageCount == indexPath.item的情况
        */
//        if images.count == indexPath.item {
//        } else {
//            cell.image = images[indexPath.item]
//        }
        // 设置 cell 的 tag
        cell.tag = indexPath.item
        if images.count != 0 {
            if images.count == indexPath.item {
                cell.image = nil
                return cell
            } else {
                cell.image = images[indexPath.item]
            }
        }
        return cell
    }
}
// MARK:--分类，实现pickerSelectorCell的代理方法
extension DYWPickerSelector:pickerSelectorCellDelegate {
    // 增加图片
    func addMoreImg() {
        print(__FUNCTION__)
//        // 使用 UIImagePickerController 调起系统相册
//        let picker = UIImagePickerController()
//        // 如果需要对获取数据进行操作，需要设置代理并且实现方法
//        picker.delegate = self
//        // 如果希望有编辑信息  需要设置
////        picker.allowsEditing = true
//        presentViewController(picker, animated: true, completion: nil)
        /*
        HMImagePickerController *picker = [[HMImagePickerController alloc] initWithSelectedAssets:self.selectedAssets];
        
        // 设置图像选择代理
        picker.pickerDelegate = self;
        // 设置目标图片尺寸
        picker.targetSize = CGSizeMake(600, 600);
        // 设置最大选择照片数量
        picker.maxPickerCount = 9;
        
        [self presentViewController:picker animated:YES completion:nil];
        */
        let picker = HMImagePickerController(selectedAssets: self.selectedAssets)
        
        picker.pickerDelegate = self
        
        picker.targetSize = CGSize(width: 600, height: 600)
        
        picker.maxPickerCount = 9
        
        self.presentViewController(picker, animated: true) { () -> Void in
            
        }
    }
    // 删除图片
    func deleteImg(cell: pickerSelectorCell) {
        print(__FUNCTION__)
        // 方法一：使用 cell 的 tag
        // 在数据源中删除数据，再刷新 collectionView
        // 根据 cell 的 tag 删除对应索引的数据
//        if images.count == cell.tag {
//            return
//        }
//        self.images.removeAtIndex(cell.tag)
//        self.collectionView?.reloadData()
        // 方法二：使用 self.collectionView?.indexPathForCell(cell) 获取对应的 indexPath.item 在删除数组中对应的数据
        guard let indexPath = self.collectionView?.indexPathForCell(cell) else {
            return
        }
        if images.count == indexPath.item {
            return
        } else {
            self.images.removeAtIndex(indexPath.item)
            self.collectionView?.reloadData()
        }
        
    }
}
//MARK:--实现 UIImagePickerController 的代理方法
extension DYWPickerSelector:HMImagePickerControllerDelegate{
    // 实现协议方法 实现了协议方法之后 dismiss 有程序员自己实现
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//////        print(image,editingInfo)
////        self.images.append(image)
////        // 刷新 collectionView
////        collectionView?.reloadData()
////        dismissViewControllerAnimated(true, completion: nil)
//        
//    }
    
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        self.images = images
        self.selectedAssets = selectedAssets!
        self.collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
        
    }
}
//MARK:--私有类
/****************************************************************/
protocol pickerSelectorCellDelegate:NSObjectProtocol {
    func addMoreImg ()
    
    func deleteImg (cell:pickerSelectorCell)
}
class pickerSelectorCell:UICollectionViewCell {
    
    var image:UIImage?{
        didSet {
            /*
            若是加载图片的 cell 则将按钮的 image 设置为 nil
            原则是设置两个不相关的属性 在不同情境下互不影响 (UIButton)
            */
            deleteBtn.hidden = image == nil
            picBtn.setImage(image, forState: .Normal)
        }
    }
    
    lazy var picBtn = UIButton(img: nil, bgImg: "compose_pic_add")
    
    lazy var deleteBtn = UIButton(img: nil, bgImg: "compose_photo_close")
    
    // 代理属性
    var delegate:pickerSelectorCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(picBtn)
        picBtn.addTarget(self, action: "didClickToAddMoreImg", forControlEvents: .TouchUpInside)
        // 设置图片的 contentModel
        picBtn.imageView?.contentMode = .ScaleAspectFill
        contentView.addSubview(deleteBtn)
        deleteBtn.addTarget(self, action: "didClickToDeleteImg", forControlEvents: .TouchUpInside)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        picBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.contentView.snp_edges)
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.contentView.snp_top).offset(2)
            make.right.equalTo(self.contentView.snp_right).offset(-2)
        }
    }
    
    // MARK:--实现点击事件
    @objc private func didClickToAddMoreImg () {
        print(__FUNCTION__)
        // 已经设置图片 不用再进行设置
        if self.image != nil {
            return
        }
        delegate?.addMoreImg()
    }
    
    @objc private func didClickToDeleteImg () {
        print(__FUNCTION__)
        delegate?.deleteImg(self)
    }
    
}
